import React, { PureComponent, Fragment } from 'react';
import {
  Table,
  Button,
  Input,
  message,
  Popconfirm,
  Divider,
  InputNumber,
  DatePicker,
  Select,
  Badge,
  Modal,
  TimePicker,
} from 'antd';
import isEqual from 'lodash/isEqual';
import styles from '../style.less';
import moment from 'moment';

const Option = Select.Option;

class MatchScoreForm extends PureComponent {
  index = 0;

  cacheOriginData = {};

  constructor(props) {
    super(props);

    this.state = {
      loading: false,
    };
  }

  static getDerivedStateFromProps(nextProps, preState) {
    if (isEqual(nextProps.value, preState.value)) {
      return null;
    }
    return {
      data: nextProps.value,
    };
  }

  getRowByKey(id, newData) {
    const { data } = this.state;
    return (newData || data).filter(item => item.id === id)[0];
  }

  toggleEditable = (e, id) => {
    e.preventDefault();
    const { data } = this.state;
    const newData = data.map(item => ({ ...item }));
    const target = this.getRowByKey(id, newData);
    if (target) {
      // 进入编辑状态时保存原始数据
      if (!target.editable) {
        this.cacheOriginData[id] = { ...target };
      }
      target.editable = !target.editable;
      this.props.onChange(newData);
      const { onChange } = this.props;
      onChange(newData);
    }
  };

  newMember = () => {
    const { data } = this.state;
    const newData = data.map(item => ({ ...item }));
    newData.push({
      bisaiCode: '',
      startTime: moment().format('YYYY-MM-DD HH:MM:SS'),
      endTime: moment().format('YYYY-MM-DD HH:MM:SS'),
      score1: null,
      score2: null,
      editable: true,
      isNew: true,
    });
    this.index += 1;
    this.props.onChange(newData);
  };

  remove(key) {
    const { data } = this.state;
    const { onChange } = this.props;
    const newData = data.filter(item => item.id !== key);
    this.props.onChange(newData);
    onChange(newData);
  }

  handleKeyPress(e, key) {
    if (e.key === 'Enter') {
      this.saveRow(e, key);
    }
  }
  handleFieldChangeDate(date, fieldName, key) {
    const { data } = this.state;
    const newData = data.map(item => ({ ...item }));
    const target = this.getRowByKey(key, newData);
    if (target) {
      target[fieldName] = date.format('HH:mm:ss');
      this.props.onChange(newData);
    }
  }

  handleFieldChangeNumber(value, fieldName, key) {
    const { data } = this.state;
    const newData = data.map(item => ({ ...item }));
    const target = this.getRowByKey(key, newData);
    if (target) {
      target[fieldName] = value;
      this.props.onChange(newData);
    }
  }

  handleFieldChangeSelect(value, fieldName, fieldName2, key) {
    const { data } = this.state;
    const newData = data.map(item => ({ ...item }));
    const target = this.getRowByKey(key, newData);

    if (target) {
      target[fieldName] = value.key;
      target[fieldName2] = value.label;
      this.props.onChange(newData);
    }
  }

  handleFieldChangeSelect2(value, fieldName, fieldName2, key) {
    const { data } = this.state;
    const newData = data.map(item => ({ ...item }));
    const target = this.getRowByKey(key, newData);
    if (target) {
      target[fieldName] = value;
      this.props.onChange(newData);
    }
  }

  handleFieldChange(e, fieldName, key) {
    const { data } = this.state;
    const newData = data.map(item => ({ ...item }));
    const target = this.getRowByKey(key, newData);
    if (target) {
      target[fieldName] = e.target.value;
      this.props.onChange(newData);
    }
  }

  saveRow(e, key) {
    e.persist();
    this.setState({
      loading: true,
    });
    setTimeout(() => {
      if (this.clickedCancel) {
        this.clickedCancel = false;
        return;
      }
      const target = this.getRowByKey(key) || {};
      console.log('target', target);
      if (!target.score1 || !target.score2) {
        message.error('请填写对阵分数。');
        e.target.focus();
        this.setState({
          loading: false,
        });
        return;
      }
      // if(target.count > (target.count-target.pickedCount)){
      //   message.error('领料数量不能超过计划。');
      //   e.target.focus();
      //   this.setState({
      //     loading: false,
      //   });
      //   return;
      // }
      delete target.isNew;
      this.props.updateScore(target);
      this.setState({
        loading: false,
      });
    }, 100);
  }

  cancel(e, key) {
    this.clickedCancel = true;
    e.preventDefault();
    const { data } = this.state;
    const newData = data.map(item => ({ ...item }));
    const target = this.getRowByKey(key, newData);
    if (this.cacheOriginData[key]) {
      Object.assign(target, this.cacheOriginData[key]);
      delete this.cacheOriginData[key];
    }
    target.editable = false;
    this.props.onChange(newData);
    this.clickedCancel = false;
  }

  getTitle = () => {
    return '成绩管理';
  };

  render() {
    console.log(this.state.data);
    const { modalVisible, modifyMatch } = this.props;

    const productOptions = this.props.productList;
    const departmentOptions = this.props.departmentList;

    const columns = [
      {
        title: modifyMatch && modifyMatch.bisaiId,
        width: 100,
        dataIndex: 'seq',
        align: 'center',
        render: value => <span>第{value}场</span>,
      },
      {
        title: modifyMatch ? modifyMatch.gamePosName1 : '',
        dataIndex: 'score1',
        align: 'center',
        width: 150,
        render: (text, record) => {
          if (record.editable) {
            return (
              <InputNumber
                value={text}
                min={0}
                onChange={e => this.handleFieldChangeNumber(e, 'score1', record.id)}
                placeholder="得分1"
              />
            );
          }
          return text;
        },
      },
      {
        title: '',
        width: 10,
        align: 'center',
        render: value => <span>:</span>,
      },
      {
        title: modifyMatch ? modifyMatch.gamePosName2 : '',
        dataIndex: 'score2',
        align: 'center',
        width: 150,
        render: (text, record) => {
          if (record.editable) {
            return (
              <InputNumber
                value={text}
                min={0}
                onChange={e => this.handleFieldChangeNumber(e, 'score2', record.id)}
                placeholder="得分2"
              />
            );
          }
          return text;
        },
      },
      {
        title: '开始时间',
        dataIndex: 'startTime',
        align: 'center',
        width: 150,
        render: (text, record) => {
          if (record.editable) {
            return (
              <TimePicker
                onChange={e => this.handleFieldChangeDate(e, 'startTime', record.id)}
                value={text ? moment(text, 'HH:mm:ss') : null}
              />
            );
          }
          return text;
        },
      },
      {
        title: '结束时间',
        dataIndex: 'endTime',
        align: 'center',
        width: 150,
        render: (text, record) => {
          if (record.editable) {
            return (
              <TimePicker
                onChange={e => this.handleFieldChangeDate(e, 'endTime', record.id)}
                value={text ? moment(text, 'HH:mm:ss') : null}
              />
            );
          }
          return text;
        },
      },

      {
        title: '操作',
        key: 'action',
        render: (text, record) => {
          const { loading } = this.state;
          if (!!record.editable && loading) {
            return null;
          }
          if (record.editable) {
            if (record.isNew) {
              return (
                <span>
                  <a onClick={e => this.saveRow(e, record.id)}>添加</a>
                  <Divider type="vertical" />
                  {/* <Popconfirm title="是否要删除此行？" onConfirm={() => this.remove(record.id)}>
                    <a>删除</a>
                  </Popconfirm> */}
                </span>
              );
            }
            return (
              <span>
                <a onClick={e => this.saveRow(e, record.id)}>确定</a>
                {/* <Divider type="vertical" />
                <a onClick={e => this.cancel(e, record.id)}>取消</a> */}
              </span>
            );
          }
          return (
            <span>
              {/* <a onClick={e => this.props.onSelect(record)}>详情</a>
              <Divider type="vertical" /> */}
              <a onClick={e => this.toggleEditable(e, record.id)}>编辑</a>
              <Divider type="vertical" />
              {/* <Popconfirm title="是否要删除此行？" onConfirm={() => this.remove(record.id)}>
                <a>删除</a>
              </Popconfirm> */}
            </span>
          );
        },
      },
    ];

    const { loading, data } = this.state;
    const { onChange } = this.props;
    this.props.onChange(data);

    return (
      <Modal
        title={this.getTitle()}
        width={1000}
        visible={modalVisible}
        onOk={this.okHandle}
        onCancel={() => this.props.close()}
        okText=""
        okButtonProps={{ disabled: true }}
        cancelText="关闭"
        maskClosable={false}
      >
        <div style={{ fontSize: 20, textAlign: 'center' }}>
          <div>
            {modifyMatch.zubieName} {modifyMatch.fenzuName}组 第{modifyMatch.round}轮{' '}
            {modifyMatch.athlethList1 &&
              modifyMatch.athlethList1
                .map(item => {
                  return item.userName;
                })
                .join(',')}{' '}
            VS{' '}
            {modifyMatch.athlethList2 &&
              modifyMatch.athlethList2
                .map(item => {
                  return item.userName;
                })
                .join(',')}
          </div>
          <div>
            {modifyMatch.placeName}{' '}
            {modifyMatch.matchDate && moment(modifyMatch.matchDate).format('YYYY-MM-DD')}{' '}
            {modifyMatch.timePhase && modifyMatch.timePhase === 'morning'
              ? '上午'
              : modifyMatch.timePhase === 'afternoon'
                ? '下午'
                : '晚上'}
          </div>
        </div>
        <Table
          loading={loading}
          columns={columns}
          dataSource={this.state.data ? this.state.data : []}
          pagination={false}
          rowClassName={record => (record.editable ? styles.editable : '')}
        />
      </Modal>
    );
  }
}

export default MatchScoreForm;
